package com.leaf.u_spring.chapter03;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jndi.JndiObjectFactoryBean;

/**
 * 不同环境所需要的数据库配置
 */
public class DataSourceDemo {

	/**
	 * EmbeddedDatabaseBuilder会搭建一个嵌入式的Hypersonic数据库
	 * 模式(schema)定义在schema.sql
	 * 测试数据通过test-data.sql加载
	 */
	@Bean(destroyMethod="shutdown")
	public DataSource dataSource_1(){
		return new EmbeddedDatabaseBuilder()
				.addScript("classpath:schema.sql")
				.addScript("classpath:test-data.sql")
				.build();
	}
	
	/**
	 * 使用JNDI从容器中获取一个DataSource
	 */
	@Bean
	public DataSource dataSource_2(){
		JndiObjectFactoryBean jndiObjectFactoryBean = new JndiObjectFactoryBean();
		jndiObjectFactoryBean.setJndiName("jdbc/myDs");
		jndiObjectFactoryBean.setResourceRef(true);
		jndiObjectFactoryBean.setProxyInterface(javax.sql.DataSource.class);
		return (DataSource) jndiObjectFactoryBean.getObject();
	}
	
	/**
	 * 配置DBCP的连接池
	 */
	@Bean(destroyMethod="close")
	public DataSource dataSource(){
		BasicDataSource dataSource = new BasicDataSource();
		dataSource.setUrl("jdbc:h2:tcp://dbserver/~/test");
		dataSource.setDriverClassName("org.h2.Driver");
		dataSource.setUsername("root");
		dataSource.setPassword("root");
		dataSource.setInitialSize(20);
		dataSource.setMaxActive(30);
		return dataSource;
	}
	
}
